<template>
  <el-row>
    <el-col style="position: relative">
      <el-divider content-position="left">系统配置</el-divider>
      <el-form
        :inline="true"
        :model="formInline"
        :rules="baseRules"
        ref="baseformref"
        class="demo-form-inline"
        style="margin-left: 20px"
      >
        <el-form-item label="批次名称" prop="batchname">
          <el-input
            v-model="formInline.batchname"
            placeholder="批次名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="电压" prop="systemvoltage">
          <el-input
            v-model="formInline.systemvoltage"
            placeholder="电压"
            clearable
          />
        </el-form-item>
        <el-form-item label="限制电流" prop="systemcurrent">
          <!-- 修正绑定字段 -->
          <el-input
            v-model="formInline.systemcurrent"
            placeholder="限制电流"
            clearable
          />
        </el-form-item>
      </el-form>
      <div style="position: absolute; top: 45px; right: 20px">
        <el-button type="primary" @click="openBatchDialogForAll">
          一键选择所有板卡用例
        </el-button>
        <!-- 批量配置按钮 -->
        <el-button
          type="primary"
          @click="openBatchDialogForSingle"
          v-if="selectedBoardId != 0"
        >
          一键选择单板卡用例
        </el-button>
        <el-button type="primary" @click="sendData">发送配置并启动</el-button>
      </div>
    </el-col>

    <el-divider content-position="left">板卡配置</el-divider>
    <el-col :span="4">
      <el-tree
        ref="treeRef"
        :data="data"
        show-checkbox
        default-expand-all
        v-model:checkedKeys="treeCheckList"
        node-key="code"
        highlight-current
        :props="defaultProps"
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
      >
        <template #default="{ node, data }">
          <span
            v-if="data.code != '0'"
            :class="{
              'board-node': true,
              active: selectedBoardId == data.code,
              hovered: node.isHovered,
            }"
            @mouseenter="node.isHovered = true"
            @mouseleave="node.isHovered = false"
          >
            {{ data.label }}</span
          >
          <span v-else> 板卡列表</span>
        </template></el-tree
      >
    </el-col>
    <el-divider direction="vertical" />
    <el-col :span="19">
      <el-checkbox-group
        v-model="checkList"
        ref="checkListRef"
        v-if="selectedBoardId"
        style="display: flex; flex-direction: row; flex-wrap: wrap; gap: 10px"
      >
        <template v-for="groupId in 5" :key="`group-${groupId}`">
          <template
            v-for="cardNumber in 12"
            :key="`group-${groupId}-card-${cardNumber}`"
          >
            <div
              style="
                min-width: 140px;
                padding: 8px;
                border: 1px solid #eee;
                border-radius: 4px;
                display: flex;
                flex-direction: column;
              "
            >
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <el-checkbox
                  :label="`${selectedBoardId}-${groupId}-${cardNumber}`"
                  @change="
                    handleCheckboxChange(
                      $event,
                      `${selectedBoardId}-${groupId}-${cardNumber}`
                    )
                  "
                  style="margin-right: 5px"
                >
                  {{ selectedBoardId }}-{{ groupId }}-{{ cardNumber }}
                </el-checkbox>
                <el-button
                  type="primary"
                  size="small"
                  @click="
                    openDialog(`${selectedBoardId}-${groupId}-${cardNumber}`)
                  "
                >
                  选择
                </el-button>
              </div>
              <div
                style="
                  margin-top: 5px;
                  font-size: 12px;
                  color: #666;
                  display: grid;
                  grid-template-columns: repeat(3, 1fr);
                  gap: 4px;
                  height: 40px;
                "
              >
                <span
                  v-if="
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                  "
                >
                  类型:
                  {{
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                      .type
                  }}
                </span>
                <span
                  v-if="
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                  "
                >
                  名称:
                  {{
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                      .name
                  }}
                </span>
                <span
                  v-if="
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                  "
                >
                  用例:
                  {{
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                      .useCase
                  }}
                </span>
                <span
                  v-if="
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                  "
                >
                  烧毁阈值:
                  {{
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                      .burnThreshold
                  }}
                </span>
                <span
                  v-if="
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                  "
                >
                  退化阈值:
                  {{
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                      .degradationThreshold
                  }}
                </span>
                <span
                  v-if="
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                  "
                >
                  退化超时:
                  {{
                    getConfigInfo(`${selectedBoardId}-${groupId}-${cardNumber}`)
                      .degradationTimeout
                  }}
                </span>
              </div>
            </div>
          </template>
        </template>
      </el-checkbox-group>
    </el-col>
    <!-- 单个配置弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`${selectedValue} 配置`"
      width="30%"
    >
      <el-form
        :model="state.formData"
        :rules="singleRules"
        label-width="80px"
        ref="formRef"
      >
        <el-form-item label="类型" prop="type">
          <el-input v-model="state.formData.type"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="state.formData.name"></el-input>
        </el-form-item>
        <el-form-item label="用例" prop="useCase">
          <el-select
            v-model="state.formData.useCase"
            placeholder="请选择测试用例"
            @change="handleTestCaseChange"
          >
            <el-option
              v-for="item in testCaseList"
              :key="item.id"
              :label="item.testCaseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="烧毁阈值" prop="burnThreshold">
          <el-input v-model="state.formData.burnThreshold"></el-input>
        </el-form-item>
        <el-form-item label="退化阈值" prop="degradationThreshold">
          <el-input v-model="state.formData.degradationThreshold"></el-input>
        </el-form-item>
        <el-form-item label="退化超时" prop="degradationTimeout">
          <el-input v-model="state.formData.degradationTimeout"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 批量配置弹窗 -->
    <el-dialog v-model="batchDialogVisible" title="批量配置" width="30%">
      <el-form
        :model="batchFormData"
        :rules="singleRules"
        label-width="80px"
        ref="batchFormRef"
      >
        <el-form-item label="类型" prop="type">
          <el-input v-model="batchFormData.type"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="batchFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="用例" prop="useCase">
          <el-select
            v-model="batchFormData.useCase"
            placeholder="请选择测试用例"
            @change="handleBatchTestCaseChange"
          >
            <el-option
              v-for="item in testCaseList"
              :key="item.id"
              :label="item.testCaseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="烧毁阈值" prop="burnThreshold">
          <el-input v-model="batchFormData.burnThreshold"></el-input>
        </el-form-item>
        <el-form-item label="退化阈值" prop="degradationThreshold">
          <el-input v-model="batchFormData.degradationThreshold"></el-input>
        </el-form-item>
        <el-form-item label="退化超时" prop="degradationTimeout">
          <el-input v-model="batchFormData.degradationTimeout"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-row>
</template>

<script setup>
import { ref, reactive } from "vue";
import { sendControl } from "@/api/device/mqttSend";
import { getTestCaseList } from "@/api/device/testcase";
import { ElMessage, ElMessageBox } from "element-plus";
const formInline = reactive({
  systemvoltage: "",
  systemcurrent: "",
  batchname: "",
});
const props = defineProps({
  datasourceindex: {
    type: String,
    default: "",
  },
  enableboardstatus: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    default: "pd",
  },
  deviceid: {
    type: String,
    default: "",
  },
});
const configList = ref([]);
const checkListRef = ref(null);

const handleCheckChange = (data, checked, indeterminate) => {
  const boardCode = data.code;
  // Bug修复：直接使用 checked 判断
  if (!checked) {
    // 从树选中列表中移除
    const treeIndex = treeCheckList.value.indexOf(boardCode);
    if (treeIndex !== -1) {
      treeCheckList.value.splice(treeIndex, 1);
    }

    // 移除该板卡下所有配置项
    const boardPrefix = `${boardCode}-`;

    checkList.value = checkList.value.filter(
      (item) => !item.startsWith(boardPrefix)
    );

    configList.value = configList.value.filter(
      (item) => !item.itemcode?.startsWith(boardPrefix)
    );

    console.log(`已移除板卡 ${boardCode} 的所有配置信息`);
  }
};
const handleCheckboxChange = (checked, label) => {
  if (!checked) {
    configList.value = configList.value.filter(
      (item) => item.itemcode != label
    );
  }
};

const baseRules = reactive({
  batchname: [{ required: true, message: "请输入批次名称", trigger: "blur" }],
  systemvoltage: [{ required: true, message: "请输入电压", trigger: "blur" }],
  systemcurrent: [
    { required: true, message: "请输入限制电流", trigger: "blur" },
  ],
});
const testCaseList = ref([]);
const handleTestCaseChange = (value) => {
  state.formData.useCase = value;
  testCaseList.value.forEach((item) => {
    if (item.id === value && item.configurationParameters) {
      let result = item.configurationParameters.value
        .replace(/"/g, "")
        .split(";");
      console.log(result);
      if (result.length === 3) {
        state.formData.burnThreshold = result[0];
        state.formData.degradationThreshold = result[1];
        state.formData.degradationTimeout = result[2];
      }
    }
  });

  console.log("测试用例选择改变", value);
};

const handleBatchTestCaseChange = (value) => {
  console.log("批量测试用例选择改变", value);
  batchFormData.useCase = value;
  testCaseList.value.forEach((item) => {
    if (item.id === value && item.configurationParameters) {
      let result = item.configurationParameters.value
        .replace(/"/g, "")
        .split(";");
      if (result.length === 3) {
        batchFormData.burnThreshold = result[0];
        batchFormData.degradationThreshold = result[1];
        batchFormData.degradationTimeout = result[2];
      }
    }
  });
};
const baseformref = ref(null);

// 存储树节点选中状态
const treeCheckList = ref([]);
// 存储复选框选中状态
const checkList = ref([]);
// 控制单个配置弹窗显示隐藏
const dialogVisible = ref(false);
// 控制批量配置弹窗显示隐藏
const batchDialogVisible = ref(false);
// 记录当前选中的复选框值
const selectedValue = ref("");
// 表单数据
const state = reactive({
  formData: {
    itemcode: "",
    type: "",
    name: "",
    useCase: "default",
    burnThreshold: "",
    degradationThreshold: "",
    degradationTimeout: "",
    systemvoltage: "",
    systemcurrent: "",
  },
});
// 批量配置表单数据
const batchFormData = reactive({
  type: "",
  name: "",
  useCase: "default",
  burnThreshold: "",
  degradationThreshold: "",
  degradationTimeout: "",
  systemvoltage: "",
  systemcurrent: "",
});

// 2. 校验规则
const singleRules = reactive({
  type: [{ required: true, message: "请输入类型", trigger: "blur" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  useCase: [{ required: true, message: "请输入用例", trigger: "blur" }],
  burnThreshold: [
    { required: true, message: "请输入烧毁阈值", trigger: "blur" },
  ],
  degradationThreshold: [
    { required: true, message: "请输入退化阈值", trigger: "blur" },
  ],
  degradationTimeout: [
    { required: true, message: "请输入退化超时", trigger: "blur" },
  ],
});
// 存储选中的板卡 id
const selectedBoardId = ref("1");
// 存储需要配置的板卡 id 列表
const batchTargetIds = ref([]);

// 树节点点击事件处理方法
const treeRef = ref(null);
const handleNodeClick = (data) => {
  // const index = treeCheckList.value.indexOf(data.code);
  // if (index === -1) {
  //   treeCheckList.value.push(data.code);
  // }
  // treeRef.value.setCheckedKeys(treeCheckList.value, false);
  selectedBoardId.value = data.code;
};
// 定义默认配置常量
const DEFAULT_THRESHOLDS = {
  burnThreshold: "80",
  degradationThreshold: "20",
  degradationTimeout: "4",
};

const defaultProps = {
  children: "children",
  label: "label",
};

const data = [
  {
    id: 0,
    label: "板卡列表",
    code: "0",
    children: [
      {
        id: 1,
        label: "功率器件板卡1",
        code: "1",
      },
      {
        id: 2,
        label: "功率器件板卡2",
        code: "2",
      },
      {
        id: 3,
        label: "功率器件板卡3",
        code: "3",
      },
      {
        id: 4,
        label: "功率器件板卡4",
        code: "4",
      },
      {
        id: 5,
        label: "功率器件板卡5",
        code: "5",
      },
      {
        id: 6,
        label: "功率器件板卡6",
        code: "6",
      },
      {
        id: 7,
        label: "功率器件板卡7",
        code: "7",
      },
      {
        id: 8,
        label: "功率器件板卡8",
        code: "8",
      },
      {
        id: 9,
        label: "功率器件板卡9",
        code: "9",
      },
      {
        id: 10,
        label: "功率器件板卡10",
        code: "10",
      },
      {
        id: 11,
        label: "功率器件板卡11",
        code: "11",
      },
      {
        id: 12,
        label: "功率器件板卡12",
        code: "12",
      },
      {
        id: 13,
        label: "功率器件板卡13",
        code: "13",
      },
      {
        id: 14,
        label: "功率器件板卡14",
        code: "14",
      },
      {
        id: 15,
        label: "功率器件板卡15",
        code: "15",
      },
      {
        id: 16,
        label: "功率器件板卡16",
        code: "16",
      },
      {
        id: 17,
        label: "功率器件板卡17",
        code: "17",
      },
      {
        id: 18,
        label: "功率器件板卡18",
        code: "18",
      },
    ],
  },
];

// 打开批量配置弹窗（所有板卡）
const openBatchDialogForAll = () => {
  const allBoardCardIds = [];
  data[0].children.forEach((board) => {
    for (let groupId = 1; groupId <= 5; groupId++) {
      for (let cardNumber = 1; cardNumber <= 12; cardNumber++) {
        allBoardCardIds.push(`${board.code}-${groupId}-${cardNumber}`);
      }
    }
  });
  batchTargetIds.value = allBoardCardIds;
  console.log(batchTargetIds);
  // 重置批量配置表单数据
  // Object.keys(batchFormData).forEach((key) => {
  //   if (key !== "useCase") {
  //     batchFormData[key] = "";
  //   } else {
  //     batchFormData.useCase = "default";
  //   }
  // });
  batchFormData.name = "";
  batchFormData.type = "";
  batchFormData.useCase = "default";
  batchFormData.burnThreshold = DEFAULT_THRESHOLDS.burnThreshold;
  batchFormData.degradationThreshold = DEFAULT_THRESHOLDS.degradationThreshold;
  batchFormData.degradationTimeout = DEFAULT_THRESHOLDS.degradationTimeout;
  batchFormData.systemvoltage = "";
  batchFormData.systemcurrent = "";
  batchDialogVisible.value = true;
};

// 打开批量配置弹窗（单张板卡）
const openBatchDialogForSingle = () => {
  if (selectedBoardId.value) {
    const singleBoardCardIds = [];
    for (let groupId = 1; groupId <= 5; groupId++) {
      for (let cardNumber = 1; cardNumber <= 12; cardNumber++) {
        singleBoardCardIds.push(
          `${selectedBoardId.value}-${groupId}-${cardNumber}`
        );
      }
    }
    batchTargetIds.value = singleBoardCardIds;
    // 重置批量配置表单数据
    // Object.keys(batchFormData).forEach((key) => {
    //   if (key !== "useCase") {
    //     batchFormData[key] = "";
    //   } else {
    //     batchFormData.useCase = "default";
    //   }
    // });
    batchFormData.name = "";
    batchFormData.type = "";
    batchFormData.useCase = "default";
    batchFormData.burnThreshold = DEFAULT_THRESHOLDS.burnThreshold;
    batchFormData.degradationThreshold =
      DEFAULT_THRESHOLDS.degradationThreshold;
    batchFormData.degradationTimeout = DEFAULT_THRESHOLDS.degradationTimeout;
    batchFormData.systemvoltage = "";
    batchFormData.systemcurrent = "";
    batchDialogVisible.value = true;
  }
};
const formRef = ref(null);
const batchFormRef = ref(null);

// 提交批量配置表单方法
const submitBatchForm = () => {
  if (!batchFormRef.value) return;
  batchFormRef.value.validate((valid) => {
    if (!valid) {
      return;
    }
    console.log("submit!");
    const boardIds = new Set(); // 用于存储板卡 id
    batchTargetIds.value.forEach((itemcode) => {
      let isUpdated = false;
      configList.value.forEach((item) => {
        if (item.itemcode === itemcode) {
          Object.assign(item, { ...batchFormData, itemcode });
          isUpdated = true;
        }
      });
      if (!isUpdated) {
        configList.value.push({ ...batchFormData, itemcode });
      }
      if (!checkList.value.includes(itemcode)) {
        checkList.value.push(itemcode);
      }
      // 提取板卡 id
      const boardId = itemcode.split("-")[0];
      boardIds.add(boardId);
    });

    // 更新树节点选中状态
    boardIds.forEach((boardId) => {
      if (!treeCheckList.value.includes(boardId)) {
        treeCheckList.value.push(boardId);
      }
    });
    treeRef.value.setCheckedKeys(treeCheckList.value, false);
    batchTargetIds.value = [];
    batchDialogVisible.value = false;
  });
}; // 打开单个配置弹窗方法
const openDialog = (value) => {
  selectedValue.value = value;
  state.formData.itemcode = value;
  const existingConfig = configList.value.find(
    (item) => item.itemcode === value
  );
  if (existingConfig) {
    Object.assign(state.formData, existingConfig);
  } else {
    state.formData.type = "";
    state.formData.name = "";
    state.formData.useCase = "default";
    state.formData.burnThreshold = DEFAULT_THRESHOLDS.burnThreshold;
    state.formData.degradationThreshold =
      DEFAULT_THRESHOLDS.degradationThreshold;
    state.formData.degradationTimeout = DEFAULT_THRESHOLDS.degradationTimeout;
    state.formData.systemvoltage = "";
    state.formData.systemcurrent = "";
  }
  dialogVisible.value = true;
};

// 发送数据方法
const sendData = () => {
  ElMessageBox.confirm("是否发送配置并启动？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    baseformref.value.validate((valid) => {
      if (!valid) {
        return;
      }
      if (checkList.value.length == 0) {
        ElMessage.warning("配置信息不能为空");
        return;
      }
      // 准备发送的数据，包含系统配置和板卡配置
      const dataToSend = {
        datasourceindex: props.datasourceindex,
        type: props.type,
        deviceid: props.deviceid,
        message: {
          type: "下发配置",
          config: configList.value,
          ...formInline,
        },
      };
      // 调用发送 API
      sendControl(dataToSend).then((res) => {
        ElMessage.success("数据下方成功");
        // 可添加成功提示
      });
    });
  });
};
// 提交单个配置表单方法
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      return;
    }
    console.log(`提交 ${selectedValue.value} 的配置表单`, state.formData);
    let isUpdated = false;
    configList.value.forEach((item) => {
      if (item.itemcode === state.formData.itemcode) {
        Object.assign(item, state.formData);
        isUpdated = true;
      }
    });
    if (!isUpdated) {
      configList.value.push({ ...state.formData });
    }
    if (!checkList.value.includes(selectedValue.value)) {
      checkList.value.push(selectedValue.value);
    }
    if (!treeCheckList.value.includes(selectedValue.value.split("-")[0])) {
      treeCheckList.value.push(selectedValue.value.split("-")[0]);
    }
    treeRef.value.setCheckedKeys(treeCheckList.value, false);
    dialogVisible.value = false;
  });
};

// 获取配置信息用于回显
const getConfigInfo = (itemcode) => {
  return configList.value.find((item) => item.itemcode === itemcode);
};
getTestCaseList({ datasourceindex: props.datasourceindex, type: "pd" }).then(
  (res) => {
    testCaseList.value = res;
    if (item.testCaseName === "default") {
      // item.configurationParameters.value="\"80;20;4\"",
      let result = item.configurationParameters.value
        .replace(/"/g, "")
        .split(";");
      if (result.length === 3) {
        DEFAULT_THRESHOLDS.burnThreshold = result[0];
        DEFAULT_THRESHOLDS.degradationThreshold = result[1];
        DEFAULT_THRESHOLDS.degradationTimeout = result[2];
      }
    }
  }
);
</script>
<style scoped>
.vertical-divider {
  height: 100%;
  border-left: 1px solid #dcdfe6; /* 竖线颜色和宽度 */
}
.board-node {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.board-node.active {
  background-color: #409eff;
  color: white;
  font-weight: bold;
}

.board-node.hovered {
  background-color: #ecf5ff;
  color: #409eff;
}

.root-node {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
  display: block;
}
</style>
